package com.gtmc.gclub.chat.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.gtmc.gclub.chat.bean.MyException;
import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.dao.TtChatLogMapper;
import com.gtmc.gclub.chat.dao.WxChatLogMapper;
import com.gtmc.gclub.chat.dao.WxUserOwnerMapper;
import com.gtmc.gclub.chat.jmessage.MessageOperator;
import com.gtmc.gclub.chat.jmessage.UserOperator;
import com.gtmc.gclub.chat.model.TmCarOwner;
import com.gtmc.gclub.chat.model.TmPotentialUser;
import com.gtmc.gclub.chat.model.TrUserEnterprise;
import com.gtmc.gclub.chat.model.TtChatLog;
import com.gtmc.gclub.chat.model.WxChatLog;
import com.gtmc.gclub.chat.model.WxUserOwner;
import com.gtmc.gclub.chat.vo.H5MessageVo;
import com.gtmc.gclub.common.WxMaterialTypeEnum;

@Service
@Transactional
public class MessageService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private WxUserOwnerMapper wxUserOwnerMapper;

	@Autowired
	private WxChatLogMapper wxChatLogMapper;

	@Autowired
	private MessageOperator messageOperator;

	@Autowired
	private UserOperator userOperator;
	
	@Autowired
	private TtChatLogMapper ttChatLogMapper;

	/**
	 * 此接口已废弃
	 * 发送微信客户的message信息
	 * 
	 * @param map
	 * @return
	 */
	public Result<Map> app2WxTransaction(TrUserEnterprise wxChatUser, TmCarOwner owner, String chatContent) {
		logger.info("发送message信息：sendMessage");
		Result<Map> result = null;
		// 查询客服用户对应表,如果没有则插入数据
		WxUserOwner userOwner = new WxUserOwner();
		userOwner.setWxUserId(wxChatUser.getId().toString());
		userOwner.setOwnerCode(owner.getPhone());// 使用电话做code
		userOwner = wxUserOwnerMapper.selectOne(userOwner);
		Date now = new Date();
		try {

			if (userOwner == null) { // 没有客服用户对应表（主表）
				userOwner = new WxUserOwner();
				userOwner.setWxUserId(wxChatUser.getId().toString());
				userOwner.setOwnerCode(owner.getPhone());

				// 获取Jmessage用户信息
				// Result<Map> ownerRst = userOperator.getUserInfo(ownerCode);
				// if(ownerRst.getReturnFlag() == 1){
				// Map data = ownerRst.getData();
				// if(data.get("avatar") != null){
				// userOwner.setOwnerIcon((String)data.get("avatar"));
				// }
				// if(data.get("nickname") != null){
				// userOwner.setOwnerName((String)data.get("nickname"));
				// }
				// }

				// 改为从app用户获取
				userOwner.setOwnerIcon(owner.getIconsPhoto());
				userOwner.setOwnerName(owner.getUserName());

				// userOwner.setOwnerImessageCode(ownerImessageCode);// 冗余！！！
				userOwner.setLastContent(chatContent);
				userOwner.setLastTime(now);
				userOwner.setDirection(ChatConstant.CHAT_DIRECTION_APP);
				userOwner.setSessionId(1);
				userOwner.setWxActiveNum(0);// 客服主动推送清零
				int i = wxUserOwnerMapper.insertSelective(userOwner);
			} else {

				int oldSessionId = userOwner.getSessionId();
				if (now.getTime() - userOwner.getLastTime().getTime() > 3 * TimeUnit.MINUTES.toMillis(1L)) {
					oldSessionId++;
				}

				userOwner.setOwnerIcon(owner.getIconsPhoto());
				userOwner.setOwnerName(owner.getUserName());

				userOwner.setLastContent(chatContent);
				userOwner.setLastTime(now);
				userOwner.setDirection(ChatConstant.CHAT_DIRECTION_APP);
				userOwner.setSessionId(oldSessionId);
				userOwner.setWxActiveNum(0);// 客服主动推送清零
				wxUserOwnerMapper.updateByPrimaryKeySelective(userOwner);
			}

			// 插入发送信息
			WxChatLog log = new WxChatLog();
			log.setContent(chatContent);
//			log.setContentType(msgType);
			log.setCrtTime(now);
			log.setDirection(ChatConstant.CHAT_DIRECTION_APP);
			// log.setWxUserId(userId);
			log.setWxUserId(wxChatUser.getId().intValue());
			log.setOwnerCode(owner.getPhone());
//			log.setSessionId(userOwner.getSessionId());
			log.setSessionId(userOwner.getId());
			int i = wxChatLogMapper.insertSelective(log);

			result = messageOperator.sendSingleTextByAdmin(wxChatUser.getJmessageCode(), owner.getPhone(), chatContent);
			// if (!"1".equals(String.valueOf(result.getReturnFlag()))) {
			if (result.getReturnFlag() != 1) {
				throw new Exception("Send message failur!!!");
			}
			Map data = result.getData();
			if (data != null) {
				try {
					Long msgId = (Long) data.get("msg_id");
					log.setMsgId(msgId);
				} catch (Exception ex) {
					logger.error("msg_id is not long ?!", ex);
				}
				try {
					wxChatLogMapper.updateByPrimaryKey(log);
				} catch (Exception e) {// 捕获不处理！
					logger.error("捕获到异常", e);
				}
			}

		} catch (Exception e) {
			logger.error("捕获到异常", e);

			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

			throw new MyException("0", "发送消息失败");
		}
		return result;
	}
	
	/**
	 * 发送微信客户的message信息
	 * 
	 * @param map
	 * @return
	 */
	public Result<Map> userToChat(TrUserEnterprise wxChatUser, TmPotentialUser owner, String chatContent,WxMaterialTypeEnum msgType,String title,String url) {
		logger.info("发送message信息：sendMessage");
		Result<Map> result = null;
		// 查询客服用户对应表,如果没有则插入数据
		WxUserOwner userOwner = new WxUserOwner();
		userOwner.setWxUserId(wxChatUser.getId().toString());
		userOwner.setOwnerCode(owner.getPotentialUserId().toString());// 使用openId做code
		userOwner.setStatus(WxUserOwner.STATUS_USEFUL);
		userOwner = wxUserOwnerMapper.selectOne(userOwner);
		Date now = new Date();
		try {
			
			if (userOwner == null) { // 没有客服用户对应表（主表）
				userOwner = new WxUserOwner();
				userOwner.setWxUserId(wxChatUser.getId().toString());
				userOwner.setOwnerCode(owner.getPotentialUserId().toString());
				
				// 获取Jmessage用户信息
				// Result<Map> ownerRst = userOperator.getUserInfo(ownerCode);
				// if(ownerRst.getReturnFlag() == 1){
				// Map data = ownerRst.getData();
				// if(data.get("avatar") != null){
				// userOwner.setOwnerIcon((String)data.get("avatar"));
				// }
				// if(data.get("nickname") != null){
				// userOwner.setOwnerName((String)data.get("nickname"));
				// }
				// }
				
				// 改为从app用户获取
				userOwner.setOwnerIcon(owner.getHeadImgurl());
				userOwner.setOwnerName(owner.getNickname());
				
				// userOwner.setOwnerImessageCode(ownerImessageCode);// 冗余！！！
				userOwner.setLastContent(chatContent);
				userOwner.setLastContentType(msgType);
				userOwner.setLastContentTitle(title);
				userOwner.setLastContentUrl(url);
				userOwner.setLastTime(now);
				userOwner.setFirstTime(now);
				userOwner.setDirection(ChatConstant.CHAT_DIRECTION_APP);
				userOwner.setSessionId(1);
				userOwner.setWxActiveNum(0);// 客服主动推送清零
				userOwner.setStatus(WxUserOwner.STATUS_USEFUL);// 更新聊天可用状态
				int i = wxUserOwnerMapper.insertSelective(userOwner);
			} else {
				
				int oldSessionId = userOwner.getSessionId();
				if (now.getTime() - userOwner.getLastTime().getTime() > 3 * TimeUnit.MINUTES.toMillis(1L)) {
					oldSessionId++;
				}
				
				userOwner.setOwnerIcon(owner.getHeadImgurl());
				userOwner.setOwnerName(owner.getNickname());
				
				userOwner.setLastContent(chatContent);
				userOwner.setLastContentType(msgType);
				userOwner.setLastContentTitle(title);
				userOwner.setLastContentUrl(url);
				userOwner.setLastTime(now);
				userOwner.setDirection(ChatConstant.CHAT_DIRECTION_APP);
				userOwner.setSessionId(oldSessionId);
				userOwner.setWxActiveNum(0);// 客服主动推送清零
				userOwner.setStatus(WxUserOwner.STATUS_USEFUL);// 更新聊天可用状态
				wxUserOwnerMapper.updateByPrimaryKeySelective(userOwner);
			}
			
			// 插入发送信息
			WxChatLog log = new WxChatLog();
			log.setContent(chatContent);
			log.setContentType(msgType);
			log.setCrtTime(now);
			log.setDirection(ChatConstant.CHAT_DIRECTION_APP);
			// log.setWxUserId(userId);
			log.setWxUserId(wxChatUser.getId().intValue());
			log.setOwnerCode(owner.getPotentialUserId().toString());
//			log.setSessionId(userOwner.getSessionId());
			log.setSessionId(userOwner.getId());
			log.setDateShow(0);
			log.setTitle(title);
			log.setUrl(url);
			int i = wxChatLogMapper.insertSelective(log);
			TtChatLog chatLog = new TtChatLog();
			chatLog.setContent(chatContent);
			chatLog.setContentType(msgType);
			chatLog.setCreateDate(new Date());
			chatLog.setPotentialUserId(owner.getPotentialUserId().toString());
			chatLog.setServiceId(userOwner.getId());
			chatLog.setSendType(1);
			logger.debug("插入消息记录：" + chatLog);
			ttChatLogMapper.insert(chatLog);
			// 这里H5接收极光消息需要很多其他的内容，在这里使用消息体做为参数沟通的媒介，传递json字符串给H5，中间加入需要的参数
//			Map<String,Object> param = new HashMap<String,Object>();
//			param.put("fromUser", owner);
//			param.put("content", chatContent);
//			param.put("contentType", msgType);
			H5MessageVo messageVo = new H5MessageVo();
			messageVo.setFromUser(owner);
			messageVo.setContent(chatContent);
			messageVo.setType(msgType);
			if(WxMaterialTypeEnum.text!=msgType) {
				messageVo.setUrl(url);
			}
			// 这里追加一个属性，标识消息来源是微信用户发送的。
			messageVo.setMessageSource(H5MessageVo.MESSAGE_FROM_WX);
			// 这里只是利用极光推送消息给PC的H5，聊天过程由系统处理。
			result = messageOperator.sendSingleTextByAdmin(wxChatUser.getJmessageCode(), owner.getPotentialUserId().toString(), JSON.toJSONString(messageVo));
			if(StringUtils.isNotEmpty(wxChatUser.getWxJmessageCode())) {
				result = messageOperator.sendSingleTextByAdmin(wxChatUser.getWxJmessageCode(), owner.getPotentialUserId().toString(), JSON.toJSONString(messageVo));
//				// PC端的H5推送消息，微信企业号的H5也要推送消息
//				Result<Map> wxResult = messageOperator.sendSingleTextByAdmin(wxChatUser.getWxJmessageCode(), "houkaihuatestSend", chatContent);
			}
			// if (!"1".equals(String.valueOf(result.getReturnFlag()))) {
			if (result.getReturnFlag() != 1) {
				throw new Exception("Send message failur!!!");
			}
			Map data = result.getData();
			if (data != null) {
				try {
					Long msgId = (Long) data.get("msg_id");
					log.setMsgId(msgId);
				} catch (Exception ex) {
					logger.error("msg_id is not long ?!", ex);
				}
				try {
					wxChatLogMapper.updateByPrimaryKey(log);
				} catch (Exception e) {// 捕获不处理！
					logger.error("捕获到异常", e);
				}
			}
			
		} catch (Exception e) {
			logger.error("捕获到异常", e);
			
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			
			throw new MyException("0", "发送消息失败");
		}
		return result;
	}
}
